package com.tensquare.user.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WF on 2019/9/23 11:01
 * jwt签权拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1.得到请求头
        String header = request.getHeader("Authorization");
        //2.判断是否以Bearer 开头
        if(StringUtils.isNotBlank(header) && header.startsWith("Bearer ")){
            //3.从第七个字符开始截取
            String token = header.substring(7);
            //4.解析token信息
            Claims claims = jwtUtil.parseJwt(token);
            //5.判断是否存在
            if(claims != null){
                request.setAttribute("claims",claims);
            }
        }
        return true;
    }
}
